package controllers;

import java.util.Date;
import java.util.List;

import models.User;
import play.data.validation.Email;
import play.data.validation.Error;
import play.data.validation.InPast;
import play.data.validation.Match;
import play.data.validation.MaxSize;
import play.data.validation.MinSize;
import play.data.validation.Required;
import play.data.validation.Validation;
import play.data.validation.Validation.ValidationResult;
import play.mvc.Controller;

public class Application extends Controller {

	public static void index() {
		List<User> us = User.findAll();
		render(us);
	}

	// public static void addUser(String firstName, String lastName,
	// String address, String phoneNum, String password, String email,
	// Date dateOfBirth) {
	public static void addUser(
			@Required @MaxSize(value = 20) @Match(value = "^[0-9a-zA-Z]+$") String firstName,

			@Required @Match(value = "^[0-9a-zA-Z]+$") @MaxSize(value = 20) String lastName,

			@MaxSize(value = 100) String address,

			@Match(value = "^[0-9\\ ]+$") String phoneNum,

			@Required @InPast Date dateOfBirth,

			@Required @MinSize(value = 10) String password,

			@Required @Email String email, @Required boolean gender) {
		if (!Validation.hasErrors()) {
			User u = new User(firstName, lastName, address, phoneNum, password,
					email, dateOfBirth, gender);
			if (User.count() < 10) {
				u.save();
			} else {
				register(u.id);
			}
		} else {
			Validation.keep();
		}
		register(0);
	}

	public static void register(long id) {
		User u = null;
		if (id != 0) {
			u = User.findById(id);
		}
		render(u);
	}

	public static void edit(long id) {
		register(id);
	}

	public static void validateFirstName(String firstName) {
		if (firstName.endsWith("lol")) {
			renderJSON(new Object[] { "firstName", true, "validation passed" });
		}
		renderJSON(new Object[] { "firstName", false, "validation failed" });
	}

	public static void validateForm(String firstName, String lastName,
			String address, String phoneNum, Date dateOfBirth, String password,
			String email) {
		renderJSON(new Object[][] {
				{ "firstName", false,
						"validation failed using ajax form validation" },
				{ "lastName", true,
						"validation passed using ajax form validation" } });
	}
}